﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using VideoClubGorbea.Metro.Proxy;
using Windows.Foundation;
using Windows.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;

namespace VideoClubGorbea.Metro
{
    partial class MainPage
    {
        MovieServicesClient client = new MovieServicesClient();
        public MainPage()
        {
            InitializeComponent();
            Observable
                .FromEvent<string>(
                    ev =>
                    {
                        searchBox.TextChanged += (s, e) =>
                        { ev((s as TextBox).Text); };
                    },
                    ev =>
                    {
                        searchBox.TextChanged += (s, e) =>
                        { ev((s as TextBox).Text); };
                    }
                )
                .Where(x => x.Count() > 4).ObserveOnDispatcher()
                .Do(s => { movieListBox.Opacity = 0.5; })
                .Throttle(TimeSpan.FromMilliseconds(400))
                .ObserveOnDispatcher()
                .SelectMany(param => SearchMovie(param))
                .Do(s => { movieListBox.Opacity = 1; movieListBox.Items.Clear(); })
                .ObserveOnDispatcher()
                .Subscribe(movie => { movieListBox.Items.Add(movie.Title); });
        }

        private List<Movie> SearchMovie(string param)
        {
            var result = client.SearchMoviesAsync(param).Result;
            return result;
        }

     

      

    }
}
